// 文件：KeyStoreHelper.java
package net.yyge.apksigner.signer.utils;

import org.spongycastle.jce.provider.BouncyCastleProvider;
import java.io.*;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.util.Locale;

public class KeyStoreHelper {

    // 单例实例
    private static final KeyStoreHelper INSTANCE = new KeyStoreHelper();

    // 懒加载的 Bouncy Castle Provider（线程安全，首次访问时初始化）
    private volatile Provider provider;

    private KeyStoreHelper() {
        // 私有构造函数
    }

    public static KeyStoreHelper getInstance() {
        return INSTANCE;
    }

    private synchronized Provider getProvider() {
        if (provider == null) {
            provider = new BouncyCastleProvider();
            Security.addProvider(provider);
        }
        return provider;
    }

    /**
     * 加载 JKS 密钥库
     */
    public static KeyStore loadJks(File jksFile, char[] password) throws Exception {
        KeyStore keyStore;
        try {
            // 注意：JksKeyStore 在 Java 中需使用组合模式实现
            keyStore = new JksKeyStore(getProviderInstance());
            InputStream is = jksFile != null ? new FileInputStream(jksFile) : null;
            try {
                keyStore.load(is, password);
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to load keystore: " + e.getMessage(), e);
        }
        return keyStore;
    }

    /**
     * 加载 BKS 密钥库
     */
    public static KeyStore loadBks(File bksFile, char[] password) throws Exception {
        KeyStore keyStore;
        try {
            keyStore = KeyStore.getInstance("BKS", "BC");
            InputStream is = bksFile != null ? new FileInputStream(bksFile) : null;
            try {
                keyStore.load(is, password);
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to load keystore: " + e.getMessage(), e);
        }
        return keyStore;
    }

    /**
     * 根据文件扩展名自动加载密钥库
     */
    public static KeyStore loadKeyStore(File keystoreFile, char[] password) throws Exception {
        String path = keystoreFile.getPath().toLowerCase(Locale.getDefault());
        if (path.endsWith(".bks")) {
            return loadBks(keystoreFile, password);
        } else {
            return loadJks(keystoreFile, password);
        }
    }

    /**
     * 创建新的密钥库（空库）
     */
    public static KeyStore createKeyStore(File keystoreFile, char[] password) throws Exception {
        String path = keystoreFile.getPath().toLowerCase(Locale.getDefault());
        if (path.endsWith(".bks")) {
            return loadBks(null, password);
        } else {
            return loadJks(null, password);
        }
    }

    /**
     * 写出密钥库到文件
     */
    public static void writeKeyStore(KeyStore ks, File keystorePath, char[] password) throws Exception {
        try (FileOutputStream fos = new FileOutputStream(keystorePath)) {
            ks.store(fos, password);
        }
    }

    /**
     * 验证明文密码是否能正确打开密钥库
     */
    public static boolean validateKeystorePassword(File keystoreFile, String password) {
        try {
            loadKeyStore(keystoreFile, password.toCharArray());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 静态辅助方法，用于获取 Provider 实例（模拟 lazy）
    private static Provider getProviderInstance() {
        return INSTANCE.getProvider();
    }
}